package org.meetunexpectedly.controller.middleground;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.meetunexpectedly.authority.Authority;
import org.meetunexpectedly.entity.video.Type;
import org.meetunexpectedly.entity.vo.BasePage;
import org.meetunexpectedly.entity.vo.Result;
import org.meetunexpectedly.service.video.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @Description: 管理分类控制器
 * @Author: pupil
 * @Date: 2024/09/05 下午 7:53
 */
@RestController
@RequestMapping("/admin/type")
public class AdminTypeController {

    @Autowired
    private TypeService typeService;

    /**
     * 根据分类id获取分类
     *
     * @param id 分类id
     * @return
     */
    @GetMapping("/{id}")
    @Authority("admin:type:get")
    public Result getType(@PathVariable Long id) {
        return Result.ok().data(typeService.getById(id));
    }

    /**
     * 分页查询分类
     *
     * @param basePage
     * @return
     */
    @GetMapping("/page")
    @Authority("admin:type:page")
    public Result getTypeByPage(BasePage basePage) {
        IPage<Type> page = typeService.page(basePage.page(), null);
        return Result.ok().data(page.getRecords()).count(page.getTotal());
    }

    /**
     * 添加分类
     *
     * @param type
     * @return
     */
    @PostMapping
    @Authority("admin:type:add")
    public Result addType(@RequestBody @Validated Type type) {
        int count = typeService.count(new LambdaQueryWrapper<Type>().eq(Type::getName, type.getName()).ne(Type::getId, type.getId()));
        if (count == 1) {
            return Result.error().message("分类已存在");
        }
        if (!typeService.save(type)) {
            return Result.error().message("添加失败");
        }
        return Result.ok().message("添加成功");
    }

    /**
     * 修改分类
     *
     * @param type
     * @return
     */
    @PutMapping
    @Authority("admin:type:update")
    public Result updateType(@RequestBody @Validated Type type) {
        int count = typeService.count(new LambdaQueryWrapper<Type>().eq(Type::getName, type.getName()).ne(Type::getId, type.getId()));
        if (count == 1) {
            return Result.error().message("分类已存在");
        }
        if (!typeService.updateById(type)) {
            return Result.error().message("修改失败");
        }

        return Result.ok().message("修改成功");

    }

    /**
     * 删除分类
     * @param id 用户
     * @return
     */
    @DeleteMapping("/{id}")
    @Authority("admin:type:delete")
    public Result deleteType(@PathVariable Long id){
        if (!typeService.removeById(id)){
            return Result.error().message("删除失败");
        }
        return Result.ok().message("删除成功");
    }
}
